
import os, time, subprocess



class reportGen():
    def __init__(self,parent):
        self.dh = parent.dh
        self.reportPath = parent.reportPath
        self.consignor_split = float(parent.consignor_split)
        self.timestamp = time.localtime()
        self.monthly_profit_dict = {}
        self.daily_profit_dict = {}
        self.monthly_internet_dict = {}
        self.monthly_in_store_dict = {}
        self.day_dict = {7:'Sunday',0:'Monday',1:'Tuesday',2:'Wednesday',3:'Thursday',4:'Friday',5:'Saturday',6:'Sunday'}
        
        for i in range(1,13):
            self.monthly_profit_dict[i] = 0.00
            self.monthly_internet_dict[i] = 0.00
            self.monthly_in_store_dict[i] = 0.00   
                     
        for i in range(0,7):
            self.daily_profit_dict[i] = 0.00

            
        self.generate_profit_report()
        self.save_reports()
        
    def generate_profit_report(self):
        for key in self.dh.cons_dict.keys():
            cons = self.dh.cons_dict[key]
            for item_key in cons.sold_dict.keys():
                item = cons.sold_dict[item_key]
                sold_location = item.sale_location
                sold_date=time.strptime(item.sold_date,'%m/%d/%Y')
                sold_price = float(item.sale_price)*self.consignor_split
                sold_month = int(sold_date.tm_mon)
                sold_wday = sold_date.tm_wday
                self.daily_profit_dict[sold_wday] = (self.daily_profit_dict[sold_wday]+sold_price)/2
                self.monthly_profit_dict[sold_month] = self.monthly_profit_dict[sold_month]+sold_price
                
                if sold_location == 'In store':
                    self.monthly_in_store_dict[sold_month] = self.monthly_in_store_dict[sold_month]+sold_price
                    print self.monthly_in_store_dict[sold_month]
                elif sold_location == 'Internet':
                    print sold_location
                    self.monthly_internet_dict[sold_month] = self.monthly_internet_dict[sold_month]+sold_price

    def save_reports(self):
        profit_report = os.path.join(self.reportPath,'Profit.csv')
        f = open(profit_report,'w')
        f.writelines('Profit by month: In Store\n')
        for key in self.monthly_in_store_dict.keys():
            f.writelines(',%i,%.2f\n' % (key,self.monthly_in_store_dict[key]))
        f.writelines('\n')    
        f.writelines('Profit by month: Internet\n')
        for key in self.monthly_internet_dict.keys():
            f.writelines(',%i,%.2f\n' % (key,self.monthly_internet_dict[key]))   
        f.writelines('\n')    
        f.writelines('Average profit by day: All\n')
        for key in self.daily_profit_dict.keys():
            f.writelines(',%s,%.2f\n' % (self.day_dict[key],self.daily_profit_dict[key])) 
        f.close()
        subprocess.call(['gnome-open',profit_report])

def start(parent):
    ins = reportGen(parent)
    
